package com.example.simin_manage.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.simin_manage.admim.dto.OrderStatisticsDTO;
import com.example.simin_manage.admim.dto.Response;
import com.example.simin_manage.entity.OrderRecord;
import com.example.simin_manage.entity.PerformancePeriod;
import com.example.simin_manage.entity.SysDept;
import com.example.simin_manage.entity.SysUser;
import com.example.simin_manage.mapper.DeptMapper;
import com.example.simin_manage.mapper.OrderMapper;
import com.example.simin_manage.mapper.PerformancePeriodMapper;
import com.example.simin_manage.mapper.SysUserMapper;
import com.example.simin_manage.service.PeriodService;
import com.example.simin_manage.service.leaderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/9/20
 */
@RestController
@RequestMapping("/api/leader")
public class LeaderController {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private PerformancePeriodMapper performancePeriodMapper;
    @Autowired
    private leaderService leaderService;
    @Autowired
    private PeriodService periodService;


    // 计算工作日（排除周六日）

    private int calcWorkDays(LocalDate start, LocalDate end) {
        int count = 0;
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            if (date.getDayOfWeek() != DayOfWeek.SATURDAY &&
                    date.getDayOfWeek() != DayOfWeek.SUNDAY) {
                count++;
            }
        }
        return count;
    }

    // ===== 周期查询 =====
    @GetMapping("/period")
    public Response leaderPeriodStats(@RequestParam Long deptId,
                                      @RequestParam(required = false) Long periodId) {
        // ⚡ 默认周期为当前月份
        if (periodId == null) {
            LocalDate now = LocalDate.now();
            PerformancePeriod currentMonth = performancePeriodMapper.selectOne(new LambdaQueryWrapper<PerformancePeriod>().ge(PerformancePeriod::getStartDate, now.withDayOfMonth(1)).le(PerformancePeriod::getEndDate, now.withDayOfMonth(now.lengthOfMonth())));
            if (currentMonth == null) return new Response(404, "当前月份周期不存在", null);
            periodId = currentMonth.getId();
        }
        PerformancePeriod period = performancePeriodMapper.selectById(periodId);
        if (period == null) return new Response(404, "周期不存在", null);

        List<SysUser> users = userMapper.selectList(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getDeptId, deptId)
                        .eq(SysUser::getRole, "member") // 排除组长
        );
//        List<SysUser> users = userMapper.selectList(new LambdaQueryWrapper<SysUser>().eq(SysUser::getDeptId, deptId));
        List<Map<String, Object>> result = new ArrayList<>();
        int deptTotalOrders = 0, deptTotalTarget = 0;
        int workDays = calcWorkDays(period.getStartDate(), period.getEndDate());
        for (SysUser user : users) {
            Number countObj = (Number) orderMapper.selectObjs(
                    new QueryWrapper<OrderRecord>()
                            .select("IFNULL(SUM(order_count),0)")
                            .eq("user_id", user.getId())
                            .ge("record_date", period.getStartDate().toString())
                            .le("record_date", period.getEndDate().toString())
            ).stream().findFirst().orElse(0);
            int orderCount = countObj.intValue();
            int userTarget = (user.getDailyTarget() == null ? 0 : user.getDailyTarget()) * workDays;
            double completionRate = userTarget == 0 ? 0 : ((double) orderCount / userTarget);
            deptTotalOrders += orderCount;
            deptTotalTarget += userTarget;
            Map<String, Object> item = new HashMap<>();
            item.put("userId", user.getId());
            item.put("username", user.getUsername());
            item.put("orderCount", orderCount);
            item.put("target", userTarget);
            item.put("nickname", user.getNickname()); // 新增字段
            item.put("completionRate", String.format("%.2f%%", completionRate * 100));
            item.put("ok", orderCount >= userTarget);
            result.add(item);
        }
        Map<String, Object> deptStats = new HashMap<>();
        deptStats.put("deptTotalOrders", deptTotalOrders);
        deptStats.put("deptTotalTarget", deptTotalTarget);
        double deptRate = deptTotalTarget == 0 ? 0 : ((double) deptTotalOrders / deptTotalTarget);
        deptStats.put("deptCompletionRate", String.format("%.2f%%", deptRate * 100));
        Map<String, Object> response = new HashMap<>();
        response.put("users", result);
        response.put("deptStats", deptStats);
        return new Response(200, "查询成功", response);
    }

    // 时间段查询
    @GetMapping("/range")
    public Response leaderRangeStats(@RequestParam Long deptId, @RequestParam String startDate, @RequestParam String endDate) {
        LocalDate start = LocalDate.parse(startDate);
        LocalDate end = LocalDate.parse(endDate);
        List<SysUser> users = userMapper.selectList(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getDeptId, deptId)
                        .eq(SysUser::getRole, "member") // 排除组长
        );
//        List<SysUser> users = userMapper.selectList(new LambdaQueryWrapper<SysUser>().eq(SysUser::getDeptId, deptId));
        List<Map<String, Object>> result = new ArrayList<>();
        int deptTotalOrders = 0, deptTotalTargetCount = 0;
        int workDays = calcWorkDays(start, end);
        // 计算工作日
        for (SysUser user : users) {
            Number countObj = (Number) orderMapper.selectObjs(
                    new QueryWrapper<OrderRecord>()
                            .select("IFNULL(SUM(order_count),0)")
                            .eq("user_id", user.getId())
                            .ge("record_date", start.toString())
                            .le("record_date", end.toString())
            ).stream().findFirst().orElse(0);
            int orderCount = countObj.intValue();
            int dailyTarget = (user.getDailyTarget() == null ? 0 : user.getDailyTarget());
            int targetCount = dailyTarget * workDays;
            // 累积目标
            deptTotalOrders += orderCount;
            deptTotalTargetCount += targetCount;
            Map<String, Object> item = new HashMap<>();
            item.put("userId", user.getId());
            item.put("username", user.getUsername());
            item.put("orderCount", orderCount);
            item.put("nickname", user.getNickname()); // 新增字段
            item.put("target", dailyTarget);
            // 每日目标
            item.put("targetCount", targetCount);
            // 累积目标（工作日）
            item.put("ok", orderCount >= targetCount);
            result.add(item);
        }
        Map<String, Object> deptStats = new HashMap<>();
        deptStats.put("deptTotalOrders", deptTotalOrders);
        deptStats.put("deptTotalTargetCount", deptTotalTargetCount);
        double deptRate = deptTotalTargetCount == 0 ? 0 : ((double) deptTotalOrders / deptTotalTargetCount);
        deptStats.put("deptCompletionRate", String.format("%.2f%%", deptRate * 100));
        Map<String, Object> response = new HashMap<>();
        response.put("users", result);
        response.put("deptStats", deptStats);
        return new Response(200, "查询成功", response);
    }


    /**
     * 根据组长ID获取所在部门信息
     */
    @GetMapping("/dept/leader/{leaderId}")
    public Response getLeaderDept(@PathVariable Long leaderId) {
        SysUser leader = userMapper.selectById(leaderId);
        if (leader == null) {
            return new Response(404, "用户不存在", null);
        }

        SysDept dept = deptMapper.selectById(leader.getDeptId());
        String deptName = dept != null ? dept.getName() : "未知部门";

        Map<String, Object> deptInfo = new HashMap<>();
        deptInfo.put("deptId", leader.getDeptId());
        deptInfo.put("deptName", deptName); // ✅ 直接从部门表查

        return new Response(200, "获取成功", deptInfo);
    }


    /**
     * 获取部门当前有效绩效周期
     */
    @GetMapping("/period/current/{deptId}")
    public Response getCurrentPeriod(@PathVariable Long deptId) {
        // 这里假设 performancePeriod 表里有 startDate、endDate
        LocalDate today = LocalDate.now();
        PerformancePeriod currentPeriod = performancePeriodMapper.selectOne(
                new LambdaQueryWrapper<PerformancePeriod>()
                        .le(PerformancePeriod::getStartDate, today)
                        .ge(PerformancePeriod::getEndDate, today)
                        .orderByDesc(PerformancePeriod::getStartDate)
        );

        if (currentPeriod == null) {
            return new Response(404, "当前周期不存在", null);
        }

        Map<String, Object> periodInfo = new HashMap<>();
        periodInfo.put("periodId", currentPeriod.getId());
        periodInfo.put("periodName", currentPeriod.getName());
        periodInfo.put("startDate", currentPeriod.getStartDate());
        periodInfo.put("endDate", currentPeriod.getEndDate());

        return new Response(200, "获取成功", periodInfo);
    }

    @GetMapping("/statistics")
    public Response getOrderStatistics(@RequestParam Long leaderId,
                                       @RequestParam(required = false,name = "userId") Long memberId,
                                       @RequestParam(required = false) String startDate,
                                       @RequestParam(required = false) String endDate,
                                       @RequestParam(required = false) Long periodId) {
        LocalDate start = (startDate != null) ? LocalDate.parse(startDate) : null;
        LocalDate end = (endDate != null) ? LocalDate.parse(endDate) : null;

        List<OrderStatisticsDTO> stats = leaderService.getOrderStatistics(leaderId, memberId, start, end, periodId);
        return new Response(200, "获取成功", stats);
    }




}

